import { defineStore } from 'pinia'
import type { RouteLocationNormalizedGeneric, RouteRecordName } from 'vue-router'
import router from '@/router'

export const useTabsStore = defineStore('tabs', () => {
// 保存页签tab的数组
  const tagList = ref<RouteLocationNormalizedGeneric[]>([])
  // keep-alive缓存的数组, 元素是组件名
  const cacheList = ref<RouteRecordName[]>([])
  const activeRoute = useRoute()
  // 添加一个页签, 如果当前路由已经打开, 则不再重复添加
  const addTagItem = (item: RouteLocationNormalizedGeneric) => {
    if (item.meta?.showInTabs ?? true) {
      if (!tagList.value.some(i => i.fullPath === item.fullPath)) {
        tagList.value.push(item)
      }
    }
  }

  // 删除一个页签
  const deleteTagItem = (fullPath: string) => {
    const index = tagList.value.findIndex(item => item.fullPath === fullPath && !item.meta?.affix)
    if (index >= 0) {
      const isActive = router.currentRoute.value.path === tagList.value[index].fullPath
      tagList.value.splice(index, 1)
      if (isActive) {
        router.push({ path: tagList.value[tagList.value.length - 1].path })
      }
    }
  }

  // 清空页签
  const clearTagList = () => {
    tagList.value = router.getRoutes().filter(item => item.meta?.affix).map(route => ({ ...route, fullPath: route.path } as unknown as RouteLocationNormalizedGeneric))
  }

  // 添加缓存页
  const addCacheItem = (item: RouteLocationNormalizedGeneric) => {
    if (!item.name) {
      return
    }
    if (item.meta?.keepAlive === false) {
      return
    }
    if (cacheList.value.includes(item.name)) {
      return
    }
    cacheList.value.push(item.name)
  }

  // 删除一个缓存页
  const deleteCacheItem = (name: RouteRecordName) => {
    const index = cacheList.value.findIndex(item => item === name)
    if (index >= 0) {
      cacheList.value.splice(index, 1)
    }
  }

  // 清空缓存页
  const clearCacheList = () => {
    cacheList.value = []
  }

  // 关闭当前
  const closeCurrent = (fullPath: string) => {
    deleteTagItem(fullPath)
    const item = tagList.value.find(i => i.fullPath === fullPath)
    if (item?.name) {
      deleteCacheItem(item.name)
    }
  }

  // 关闭其他
  const closeOther = (fullPath: string) => {
    const arr = tagList.value.filter(i => i.fullPath !== fullPath)
    arr.forEach((item) => {
      deleteTagItem(item.fullPath)
      if (item?.name) {
        deleteCacheItem(item.name)
      }
    })
  }

  // 关闭全部
  const closeAll = () => {
    clearTagList()
    router.push({ path: '/' })
  }

  // 重置
  const reset = () => {
    clearTagList()
    clearCacheList()
  }

  reset()

  watch(() => activeRoute.path, () => {
    const item = { ...activeRoute } as RouteLocationNormalizedGeneric
    addTagItem(item)
    addCacheItem(item)
  }, { immediate: true })

  return {
    tagList,
    cacheList,
    addTagItem,
    deleteTagItem,
    clearTagList,
    addCacheItem,
    deleteCacheItem,
    clearCacheList,
    closeCurrent,
    closeOther,
    closeAll,
    reset,
  }
})
